/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fjala.softure.tree.array;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.fjala.softure.tree.Node;

/**
 * It is used to travel a tree.
 *
 * @author Jorge Lopez.
 * @author Manolo Alvarez.
 */
public class ArrayBinaryIterator<E> implements Iterator<E> {

    /**
     * List of the nodes.
     */
    private List<E> nodes;

    /**
     * Index iterator.
     */
    private int index = 0;

    /**
     * This constructor that collects a data according to the root.
     *
     * @param root of a tree.
     */
    public ArrayBinaryIterator(Node<E> root) {
        nodes = new ArrayList<E>();
        nodes.add(root.getData());
        collect(root);
    }

    /**
     * Collects data of the root.
     *
     * @param root root of a tree.
     */
    private void collect(Node<E> root) {
        if (root.hasChildren()) {
            for (Node<E> node : root.getChildren()) {
                if (node != null) {
                    nodes.add(node.getData());
                    collect(node);
                }
            }
        }
    }

    @Override
    public boolean hasNext() {
        return index < nodes.size();
    }

    @Override
    public E next() {
        E e = nodes.get(index);
        index++;
        return e;
    }

    @Override
    public void remove() {
        nodes.remove(nodes.get(index));
    }
}
